package com.topisv.tms.utils;

import static com.google.common.base.Preconditions.checkArgument;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springside.modules.mapper.JsonMapper;

import com.google.common.base.Charsets;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.hash.Hashing;
import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.EdiOrderItem;
import com.topisv.tms.entity.ExpressConfigure;
import com.topisv.tms.entity.WarehouseAddress;
import com.topisv.tms.utils.sf.Util;
import com.topisv.tms.utils.sto.vo.OrderInfo;
import com.topisv.tms.utils.ttkd.DayMailConstants;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 
 * 获取快递公司运单号工具类
 *
 * @author <a href=mailto:zhangweize@nryuncang.com>zhangweize</a>
 * @version 1.0.0
 */
public class ExpressUtil {
	// 常量
	private static final Charset UTF_8 = Charsets.UTF_8;
	private static final String STYLE = "json";
	private static final String CHARSET_STR = UTF_8.name();


	
	/**
	 * Base64编码
	 * 
	 * @param bs
	 * @return [参数说明]
	 * @author <a href=mailto:zhangweize@nryuncang.com>zhangweize</a>
	 * @version 1.0.0
	 */
	public static String encryptBASE64(byte[] bs) {
		return Base64.encodeBase64String(bs);
	}
	 /**
     * @param data
     * @return
     */
	public static String encryptBASE64(String data) {
        return Base64.encodeBase64String(data.getBytes(UTF_8));
    }
	
	  /**
     * @param data
     * @return
     */
    public static String digestMD5ZTO(String data) {
        return Hashing.md5().hashString(data, UTF_8).toString();
    }
	/**
	 * 
	 * 
	 * MD5加密
	 * 
	 * @param data
	 * @return [参数说明]
	 * @author <a href=mailto:zhangweize@nryuncang.com>zhangweize</a>
	 * @version 1.0.0
	 */
	public static byte[] digestMD5(String data) {
//		return Hashing.md5().hashString(data, UTF_8).toString();
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(data.getBytes("utf8"));
			return md5.digest();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 传递的参数进行编码 UTF8
	 * 
	 *
	 * @param data
	 * @return [参数说明]
	 * @author <a href=mailto:zhangweize@nryuncang.com>zhangweize</a>
	 * @version 1.0.0
	 */
	public static String urlEncode(String data) {
		try {
			return URLEncoder.encode(data, CHARSET_STR);
		} catch (UnsupportedEncodingException e) {
			return data;
		}
	}

	/**
	 * 
	 * 当前时间格式化
	 *
	 * @return [参数说明]
	 * @author <a href=mailto:zhangweize@nryuncang.com>zhangweize</a>
	 * @version 1.0.0
	 */
	public static String formatDateNow() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return sdf.format(new Date());
	}
	/**
	 * 
	 * Map转化成XML，但是去掉了声明  <?xml version="1.0" encoding="UTF-8"?>
	 *
	 * @param vo 
	 * @param rootElement 根节点
	 * @return [参数说明]
	 * @author <a href=mailto:zhangweize@nryuncang.com>zhangweize</a>
	 * @version 1.0.0
	 */
	 public static String map2xmlBody(Map<String, Object> vo, String rootElement) {
//	        org.dom4j.Document doc = DocumentHelper.createDocument();
	        Element body = DocumentHelper.createElement(rootElement);
//	        doc.add(body);
	        __buildMap2xmlBody(body, vo);
	        return body.asXML();
	    }
	     
	    private static void __buildMap2xmlBody(Element body, Map<String, Object> vo) {
	        if (vo != null) {
	            Iterator<String> it = vo.keySet().iterator();
	            while (it.hasNext()) {
	                String key = (String) it.next();
	                if (StringUtils.isNotEmpty(key)) {
	                    Object obj = vo.get(key);
	                    Element element = DocumentHelper.createElement(key);
	                    if (obj != null) {
	                        if (obj instanceof java.lang.String) {
	                            element.setText((String) obj);
	                        } else {
	                            if (obj instanceof java.lang.Character || obj instanceof java.lang.Boolean || obj instanceof java.lang.Number
	                                    || obj instanceof java.math.BigInteger || obj instanceof java.math.BigDecimal) {
//	                                org.dom4j.Attribute attr = DocumentHelper.createAttribute(element, "type", obj.getClass().getCanonicalName());
//	                                element.add(attr);
	                                element.setText(String.valueOf(obj));
	                            } else if (obj instanceof java.util.Map) {
//	                                org.dom4j.Attribute attr = DocumentHelper.createAttribute(element, "type", java.util.Map.class.getCanonicalName());
//	                                element.add(attr);
	                                __buildMap2xmlBody(element, (Map<String, Object>) obj);
	                            } else {
	                            }
	                        }
	                    }
	                    body.add(element);
	                }
	            }
	        }
	    }
	    public static void main(String[] args) {
			//String xml = loadFile(args[0]);
			//String checkword = loadFile(args[1]);
			//System.out.println(md5EncryptAndBase64(xml + checkword));
			//System.out.println(md5EncryptAndBase64("abc"));
			System.out.println(encryptBASE64(digestMD5("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Request service=\"OrderService\" lang=\"zh-CN\"><Head>5715044232</Head><Body><Order orderid=\"PD145758503748578\" express_type=\"37\" pay_method=\"1\" j_company=\"杭州能容物联网科技有限公司\" j_contact=\"天天云仓\" j_tel=\"0571-86906575\" j_province=\"浙江省\" j_city=\"杭州市\" j_address=\"滨康路101号海威大厦\" d_contact=\"测试赵四\" d_tel=\"13800000008\" d_province=\"浙江省\" d_city=\"杭州市\" d_address=\"浙江省杭州市滨江区滨康路海威大厦107号\" custid=\"5715044232\" parcel_quantity=\"1\" is_gen_bill_no=\"1\"><Cargo name=\"测试产品 红色170测试产品 红色170\" count=\"1\" unit=\"\" amount=\"null\"/></Order></Body></Request>RP4jfKIvUZOp6GbcM7GHTFmSDRzohjhV")));
			//System.out.println(md5EncryptAndBase64("中"));
		}
}
